const { spawn } = require('child_process')
const path = require('path')
const net = require('net')

class DlvManager {
  constructor() {
    this.dlvProcess = null
    this.dlvClient = null
    this.apiPort = 2345
    this.headlessMode = true
    this.currentState = 'stopped' // stopped, running, paused
    this.breakpoints = new Map()
    this.nextBreakpointId = 1
    this.dlvPath = 'dlv' // dlv可执行文件路径
    this.responseBuffer = '' // 用于缓冲不完整的 JSON 响应
    this.requestQueue = [] // 请求队列
    this.pendingRequests = new Map() // 待处理的请求
    this.maxConcurrentRequests = 5 // 最大并发请求数
    this.activeRequests = 0 // 当前活跃请求数
    this.pollingInterval = 100 // 轮询间隔（毫秒），默认100ms
    this.listeners = {} // 事件监听器
    this.statePollingTimer = null // 状态轮询定时器
  }

  /**
   * 设置dlv路径
   * @param {string} path - dlv可执行文件路径
   */
  setDlvPath(path) {
    this.dlvPath = path
  }

  /**
   * 设置轮询间隔
   * @param {number} interval - 轮询间隔（毫秒）
   */
  setPollingInterval(interval) {
    if (interval && interval >= 50 && interval <= 1000) {
      this.pollingInterval = interval
      // 如果正在轮询，重新启动以应用新间隔
      if (this.statePollingTimer) {
        this.stopStatePolling()
        this.startStatePolling()
      }
    }
  }

  /**
   * 查找可用端口
   */
  async findAvailablePort(startPort = 2345) {
    const maxPort = 2400

    for (let port = startPort; port <= maxPort; port++) {
      if (await this.isPortAvailable(port)) {
        return port
      }
    }

    throw new Error(`无法找到可用端口 (${startPort}-${maxPort})`)
  }

  /**
   * 检查端口是否可用
   */
  isPortAvailable(port) {
    return new Promise((resolve) => {
      const server = net.createServer()

      server.once('error', (err) => {
        if (err.code === 'EADDRINUSE') {
          resolve(false)
        } else {
          resolve(false)
        }
      })

      server.once('listening', () => {
        server.close(() => {
          // 关闭后稍微延迟，确保端口完全释放
          setTimeout(() => {
            resolve(true)
          }, 100)
        })
      })

      server.listen(port, '127.0.0.1')
    })
  }

  /**
   * 启动dlv调试器
   * @param {string} programPath - Go程序路径
   * @param {Array} args - 程序参数
   * @returns {Promise}
   */
  async startDebugger(programPath, args = []) {
    if (this.dlvProcess) {
      throw new Error('调试器已在运行')
    }

    // 查找可用端口
    try {
      this.apiPort = await this.findAvailablePort(2345)
      this.emit('output', { type: 'info', data: `找到可用端口: ${this.apiPort}\n` })
    } catch (error) {
      const errMsg = '无法找到可用端口: ' + error.message
      throw new Error(errMsg)
    }

    return new Promise((resolve, reject) => {
      try {
        // 构建dlv命令
        const dlvArgs = [
          'exec',
          programPath,
          '--headless',
          '--api-version=2',
          `--listen=127.0.0.1:${this.apiPort}`,
          '--accept-multiclient',
          '--check-go-version=false',
          '--log'
        ]

        if (args.length > 0) {
          dlvArgs.push('--')
          dlvArgs.push(...args)
        }

        // 启动dlv进程
        const dlvCommand = `${this.dlvPath} ${dlvArgs.join(' ')}`
        this.emit('output', { type: 'info', data: `启动 DLV: ${dlvCommand}\n` })

        this.dlvProcess = spawn(this.dlvPath, dlvArgs, {
          cwd: path.dirname(programPath),
          stdio: ['pipe', 'pipe', 'pipe']
        })

        // 监听输出
        this.dlvProcess.stdout.on('data', (data) => {
          const output = data.toString()
          this.emit('output', { type: 'stdout', data: output })

          // 检测dlv是否已准备好（在stdout中检测）
          if (output.includes('API server listening')) {
            this.connectToDebugger().then(() => {
              this.currentState = 'paused'
              resolve({ success: true, message: '调试器启动成功' })
            }).catch(reject)
          }
        })

        this.dlvProcess.stderr.on('data', (data) => {
          const output = data.toString()
          this.emit('output', { type: 'stderr', data: output })

          // 检测端口冲突错误
          if (output.includes('bind:') && output.includes('address') && output.includes('port')) {
            this.cleanup()
            reject(new Error('端口冲突，请重试'))
            return
          }
        })

        this.dlvProcess.on('error', (error) => {
          this.emit('error', { message: `进程错误: ${error.message}` })
          reject(error)
        })

        this.dlvProcess.on('exit', (code, signal) => {
          this.currentState = 'stopped'
          this.emit('exit', { code, signal })
          this.cleanup()
        })

        // 设置超时
        setTimeout(() => {
          if (this.currentState === 'stopped') {
            reject(new Error('调试器启动超时'))
          }
        }, 10000)

      } catch (error) {
        reject(error)
      }
    })
  }

  /**
   * 连接到dlv API服务器
   */
  connectToDebugger() {
    return new Promise((resolve, reject) => {
      this.dlvClient = new net.Socket()

      this.dlvClient.connect(this.apiPort, '127.0.0.1', () => {
        resolve()
      })

      this.dlvClient.on('error', (error) => {
        reject(error)
      })

      this.dlvClient.on('data', (data) => {
        // 将接收到的数据添加到缓冲区
        this.responseBuffer += data.toString()

        // 按行分割，处理完整的 JSON 行
        const lines = this.responseBuffer.split('\n')

        // 保留最后一个可能不完整的行
        this.responseBuffer = lines.pop() || ''

        // 处理每一行完整的 JSON
        for (const line of lines) {
          if (!line.trim()) continue

          try {
            const response = JSON.parse(line)
            this.emit('api-response', response)
          } catch (e) {
            console.error('[DLV Manager] JSON解析失败:', line, e)
          }
        }
      })
    })
  }

  /**
   * 发送API请求到dlv
   * @param {number} timeout - 超时时间（毫秒），默认 5000ms
   */
  sendApiRequest(method, params = {}, timeout = 5000) {
    return new Promise((resolve, reject) => {
      if (!this.dlvClient) {
        return reject(new Error('未连接到调试器'))
      }

      const request = {
        method: 'RPCServer.' + method,
        params: [params],
        id: Date.now()
      }

      const requestStr = JSON.stringify(request) + '\n'

      const responseHandler = (response) => {
        if (response.id === request.id) {
          this.removeListener('api-response', responseHandler)
          if (response.error) {
            // 记录详细的错误信息
            const errorMsg = response.error.message || response.error.data || JSON.stringify(response.error) || '请求失败'

            // 只有非 "unable to find function context" 错误才打印日志
            // 这个错误在程序刚启动或运行时是正常的，不需要打印
            if (!errorMsg.includes('unable to find function context')) {
              console.error('[DLV Manager] API 错误响应:', JSON.stringify(response.error, null, 2))
            }

            reject(new Error(errorMsg))
          } else {
            resolve(response.result)
          }
        }
      }

      this.on('api-response', responseHandler)
      this.dlvClient.write(requestStr)

      // 超时处理
      const timeoutId = setTimeout(() => {
        this.removeListener('api-response', responseHandler)
        reject(new Error('请求超时'))
      }, timeout)

      // 确保响应时清除超时
      const originalHandler = responseHandler
      const wrappedHandler = (response) => {
        if (response.id === request.id) {
          clearTimeout(timeoutId)
          originalHandler(response)
        }
      }
      this.removeListener('api-response', responseHandler)
      this.on('api-response', wrappedHandler)
    })
  }

  /**
   * 继续执行程序
   */
  async continue() {
    try {
      this.currentState = 'running'

      // continue 命令是阻塞的，会等到断点命中或程序退出才返回
      // 因此我们需要异步处理，不等待响应
      this.sendContinueCommand()

      return { success: true, message: '继续执行' }
    } catch (error) {
      console.error('[DLV Manager] continue 命令失败:', error)
      return { success: false, message: error.message }
    }
  }

  /**
   * 发送 continue 命令（异步，不等待响应）
   */
  async sendContinueCommand() {
    try {
      // continue 命令会阻塞直到断点命中或程序退出
      // 使用 60 秒超时，因为程序可能运行较长时间才命中断点
      const result = await this.sendApiRequest('Command', { name: 'continue' }, 60000)

      // 检查返回的状态
      const state = result.State
      if (state) {
        // 保存当前 goroutine ID
        if (state.currentGoroutine) {
          this.currentGoroutineID = state.currentGoroutine.id
        }

        // 检查是否在断点处
        if (!state.Running && state.currentThread && state.currentThread.breakPoint) {
          this.currentState = 'paused'
          this.emit('breakpoint-hit', { state, goroutineID: this.currentGoroutineID })
        } else if (state.exited) {
          // 程序已退出，清理资源
          this.currentState = 'stopped'
          this.emit('program-exited', { exitStatus: state.exitStatus })
          // 等待一小段时间让前端接收事件，然后清理
          setTimeout(() => {
            this.cleanup()
          }, 100)
        } else {
          // 如果状态未知，启动轮询
          this.startStatePolling()
        }
      }
    } catch (error) {
      console.error('[DLV Manager] continue 命令异常:', error)
      // 如果是超时错误，说明程序还在运行，启动轮询
      if (error.message === '请求超时') {
        this.startStatePolling()
      }
    }
  }

  /**
   * 启动状态轮询，检测断点命中
   */
  startStatePolling() {
    // 清除之前的轮询
    if (this.statePollingTimer) {
      clearInterval(this.statePollingTimer)
    }

    // 使用配置的轮询间隔检查状态
    this.statePollingTimer = setInterval(async () => {
      try {
        const state = await this.getState()

        if (!state) {
          this.stopStatePolling()
          return
        }

        // 检查是否在断点处 (Running=false 且有 breakPoint)
        if (!state.running && state.currentThread && state.currentThread.breakPoint) {
          this.currentState = 'paused'
          this.stopStatePolling()
          this.emit('breakpoint-hit', { state })
          return
        }

        // 检查程序是否退出
        if (state.exited) {
          this.currentState = 'stopped'
          this.stopStatePolling()
          this.emit('program-exited', { exitStatus: state.exitStatus })
          // 等待一小段时间让前端接收事件，然后清理
          setTimeout(() => {
            this.cleanup()
          }, 100)
        }
      } catch (error) {
        console.error('[DLV Manager] 状态轮询错误:', error)
      }
    }, this.pollingInterval)
  }

  /**
   * 停止状态轮询
   */
  stopStatePolling() {
    if (this.statePollingTimer) {
      clearInterval(this.statePollingTimer)
      this.statePollingTimer = null
    }
  }

  /**
   * 单步执行（步过）
   */
  async stepOver() {
    try {
      await this.sendApiRequest('Command', { name: 'next' })
      this.currentState = 'paused'
      const state = await this.getState()
      return { success: true, state }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 单步执行（步入）
   */
  async stepInto() {
    try {
      await this.sendApiRequest('Command', { name: 'step' })
      this.currentState = 'paused'
      const state = await this.getState()
      return { success: true, state }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 单步执行（步出）
   */
  async stepOut() {
    try {
      await this.sendApiRequest('Command', { name: 'stepOut' })
      this.currentState = 'paused'
      const state = await this.getState()
      return { success: true, state }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 暂停执行
   */
  async pause() {
    try {
      await this.sendApiRequest('Command', { name: 'halt' })
      this.currentState = 'paused'
      return { success: true, message: '已暂停' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 设置断点
   * @param {string} file - 文件路径
   * @param {number} line - 行号
   * @param {string} condition - 可选的条件表达式
   * @param {string} hitCondition - 可选的命中次数条件 (如 "> 5", "% 10 == 0")
   */
  async setBreakpoint(file, line, condition = null, hitCondition = null) {
    try {
      const breakpointData = {
        file: file,
        line: line
      }

      // 如果有条件，添加到断点数据中
      if (condition && condition.trim()) {
        breakpointData.cond = condition.trim()
      }

      // 如果有命中次数条件，添加到断点数据中
      if (hitCondition && hitCondition.trim()) {
        breakpointData.hitCond = hitCondition.trim()
      }

      const result = await this.sendApiRequest('CreateBreakpoint', {
        Breakpoint: breakpointData
      })

      const id = this.nextBreakpointId++
      this.breakpoints.set(id, {
        id,
        file,
        line,
        condition: condition || null,
        hitCondition: hitCondition || null,
        dlvId: result.Breakpoint.id,
        hitCount: 0 // 记录命中次数
      })

      return { success: true, breakpoint: this.breakpoints.get(id) }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 删除断点
   */
  async clearBreakpoint(id) {
    try {
      const breakpoint = this.breakpoints.get(id)
      if (!breakpoint) {
        return { success: false, message: '断点不存在' }
      }

      await this.sendApiRequest('ClearBreakpoint', { Id: breakpoint.dlvId })
      this.breakpoints.delete(id)

      return { success: true, message: '断点已删除' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 获取所有断点
   */
  getBreakpoints() {
    return Array.from(this.breakpoints.values())
  }

  /**
   * 获取源文件列表
   */
  async listSources(filter = '') {
    try {
      const result = await this.sendApiRequest('ListSources', {
        Filter: filter
      })

      let sources = result.Sources || []

      // 过滤掉标准库和第三方依赖的文件，只保留项目中的文件
      sources = sources.filter(source => {
        // 排除 Go 标准库路径（通常包含 /go/src/ 或 GOROOT）
        if (source.includes('/go/src/') ||
            source.includes('\\go\\src\\') ||
            source.includes('/usr/local/go/src/') ||
            source.includes('/usr/lib/go/src/')) {
          return false
        }

        // 排除第三方模块路径（通常在 GOPATH/pkg/mod 或包含 @v）
        if (source.includes('/pkg/mod/') ||
            source.includes('\\pkg\\mod\\') ||
            source.includes('@v')) {
          return false
        }

        // 排除 Go 缓存路径
        if (source.includes('/.cache/') || source.includes('\\.cache\\')) {
          return false
        }

        return true
      })

      return {
        success: true,
        sources: sources
      }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 获取当前状态
   */
  async getState() {
    try {
      const result = await this.sendApiRequest('State')

      // dlv 返回的数据结构是 { State: {...} }
      const state = result.State || result

      return {
        currentThread: state.currentThread,
        currentGoroutine: state.currentGoroutine,
        exited: state.exited,
        exitStatus: state.exitStatus,
        running: state.Running,
        threads: state.Threads
      }
    } catch (error) {
      console.error('[DLV Manager] getState 错误:', error)
      return null
    }
  }

  /**
   * 获取调用堆栈
   * @param {number} depth - 堆栈深度，默认 50
   * @param {number} goroutineID - 可选的 Goroutine ID，如果不提供则获取当前 goroutine 的堆栈
   */
  async getStacktrace(depth = 50, goroutineID = -1) {
    try {
      // 使用 Stacktrace API 获取指定 goroutine 的堆栈
      const result = await this.sendApiRequest('Stacktrace', {
        Id: goroutineID,
        Depth: depth,
        Full: false,
        Cfg: {
          FollowPointers: true,
          MaxVariableRecurse: 1,
          MaxStringLen: 64,
          MaxArrayValues: 64,
          MaxStructFields: -1
        }
      })

      // 解析堆栈帧
      const frames = (result.Locations || []).map(loc => ({
        pc: loc.pc || 0,
        file: loc.file || 'unknown',
        line: loc.line || 0,
        function: loc.function?.name || 'unknown'
      }))

      return {
        success: true,
        frames: frames
      }
    } catch (error) {
      console.error('[DLV Manager] 获取堆栈失败:', error)
      return { success: false, message: error.message }
    }
  }

  /**
   * 获取局部变量
   * @param {number} goroutineID - Goroutine ID，默认 -1 表示当前 goroutine
   * @param {number} frameIndex - 栈帧索引，默认 0 表示当前栈帧
   * @param {number} maxDepth - 最大递归深度，默认 3
   */
  async getLocalVariables(goroutineID = -1, frameIndex = 0, maxDepth = 3) {
    try {
      // 根据深度动态调整超时时间：每增加1层深度，增加2秒超时
      // 基础超时5秒 + (深度 * 2秒)
      const timeout = 5000 + (maxDepth * 2000)

      const result = await this.sendApiRequest('ListLocalVars', {
        Scope: {
          GoroutineID: goroutineID,
          Frame: frameIndex
        },
        Cfg: {
          FollowPointers: true,       // 跟随指针，以便能展开指针类型
          MaxVariableRecurse: maxDepth,  // 使用配置的深度
          MaxStringLen: 200,
          MaxArrayValues: 64,
          MaxStructFields: -1         // 加载所有结构体字段（-1表示全部）
        }
      }, timeout)  // 使用动态超时时间

      return {
        success: true,
        variables: result.Variables || []
      }
    } catch (error) {
      // 只有非 "unable to find function context" 错误才打印日志
      if (!error.message.includes('unable to find function context')) {
        console.error('[DLV Manager] getLocalVariables 错误:', error)
      }
      return { success: false, message: error.message }
    }
  }

  /**
   * 求值表达式
   * @param {string} expression - 表达式
   * @param {number} maxDepth - 最大递归深度，默认 3（与局部变量深度配置一致）
   */
  async evaluate(expression, maxDepth = 3) {
    try {
      // 根据深度动态调整超时时间：每增加1层深度，增加2秒超时
      // 基础超时5秒 + (深度 * 2秒)
      const timeout = 5000 + (maxDepth * 2000)

      const result = await this.sendApiRequest('Eval', {
        Scope: { GoroutineID: -1 },
        Expr: expression,
        Cfg: {
          FollowPointers: true,
          MaxVariableRecurse: maxDepth,  // 使用可配置的深度
          MaxStringLen: 200,
          MaxArrayValues: 100,           // 增加数组元素限制
          MaxStructFields: -1            // -1 表示加载所有字段
        }
      }, timeout)  // 使用动态超时时间

      return {
        success: true,
        variable: result.Variable
      }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  /**
   * 设置变量值
   * @param {string} symbol - 变量名或表达式（如 "myVar" 或 "user.name"）
   * @param {string} value - 新的值
   * @param {number} goroutineID - Goroutine ID
   * @param {number} frameIndex - 栈帧索引
   */
  async setVariable(symbol, value, goroutineID = -1, frameIndex = 0) {
    try {
      const scope = {
        GoroutineID: goroutineID,
        Frame: frameIndex,
        DeferredCall: 0
      }

      this.emit('output', {
        type: 'info',
        data: `[setVariable] 尝试设置变量: ${symbol} = ${value} (Goroutine: ${goroutineID}, Frame: ${frameIndex})\n`
      })

      // 方法1: 先尝试使用 Set API (适用于数字、布尔等简单类型)
      const setParams = {
        Scope: scope,
        Symbol: symbol,
        Value: value
      }

      try {
        const result = await this.sendApiRequest('Set', setParams)

        // 验证修改是否成功 - 重新读取变量值
        try {
          const verifyResult = await this.sendApiRequest('Eval', {
            Scope: scope,
            Expr: symbol,
            Cfg: {
              FollowPointers: true,
              MaxVariableRecurse: 1,
              MaxStringLen: 200,
              MaxArrayValues: 64,
              MaxStructFields: -1
            }
          })

          const newValue = verifyResult.Variable?.value

          this.emit('output', {
            type: 'info',
            data: `[setVariable] 变量设置成功: ${symbol} = ${newValue}\n`
          })
        } catch (verifyError) {
          this.emit('output', {
            type: 'info',
            data: `[setVariable] 变量设置成功: ${symbol}\n`
          })
        }

        return {
          success: true,
          message: '变量修改成功',
          result: result
        }
      } catch (setError) {
        // Set API 失败,提供友好的错误信息
        console.error('[DLV Manager] Set API 失败:', setError.message)
        throw setError
      }
    } catch (error) {
      console.error('[DLV Manager] setVariable 错误:', error)

      // 提供更友好的错误信息
      let userMessage = error.message

      if (error.message.includes('can not be allocated') ||
          error.message.includes('function calls are not allowed')) {
        userMessage = '无法修改此变量:Delve 不支持修改需要内存分配的类型(如字符串、切片等)。\n\n' +
                     '可以修改的类型:\n' +
                     '✓ 数字类型 (int, float, etc.)\n' +
                     '✓ 布尔类型 (bool)\n' +
                     '✓ 指针指向的值\n\n' +
                     '不支持修改的类型:\n' +
                     '✗ 字符串 (string)\n' +
                     '✗ 切片 (slice)\n' +
                     '✗ 映射 (map)\n' +
                     '✗ 接口 (interface)'
      }

      this.emit('output', {
        type: 'stderr',
        data: `[setVariable] 设置变量失败: ${symbol} = ${value}\n错误: ${userMessage}\n`
      })

      return {
        success: false,
        message: userMessage
      }
    }
  }

  /**
   * 加载变量的子成员（用于按需展开结构体、数组等复杂类型）
   * @param {string} expr - 变量表达式（如 "myStruct" 或 "myArray[0]"）
   * @param {number} goroutineID - Goroutine ID
   * @param {number} frameIndex - 栈帧索引
   */
  async loadVariableChildren(expr, goroutineID = -1, frameIndex = 0) {
    try {
      // 验证表达式
      if (!expr || typeof expr !== 'string') {
        throw new Error('表达式不能为空')
      }

      const trimmedExpr = expr.trim()
      if (!trimmedExpr) {
        throw new Error('表达式不能为空')
      }

      // 检查表达式是否以.结尾或包含连续的点
      if (trimmedExpr.endsWith('.') || trimmedExpr.includes('..')) {
        throw new Error('表达式格式不正确: ' + trimmedExpr)
      }

      const result = await this.sendApiRequest('Eval', {
        Scope: {
          GoroutineID: goroutineID,
          Frame: frameIndex
        },
        Expr: trimmedExpr,
        Cfg: {
          FollowPointers: true,       // 跟随指针
          MaxVariableRecurse: 8,      // 加载 5 层深度（增加以支持更深层级的变量）
          MaxStringLen: 200,
          MaxArrayValues: 64,
          MaxStructFields: -1         // 加载所有字段
        }
      })

      return {
        success: true,
        variable: result.Variable
      }
    } catch (error) {
      console.error('[DLV Manager] loadVariableChildren 错误:', error)
      return { success: false, message: error.message }
    }
  }

  /**
   * 获取 Goroutine 列表
   */
  async listGoroutines() {
    try {
    
      // 尝试不传递参数或者传递空对象
      const result = await this.sendApiRequest('ListGoroutines', {})

  



      const goroutines = (result.Goroutines || []).map(g => ({
        id: g.id,
        currentLoc: {
          file: g.userCurrentLoc?.file || 'unknown',
          line: g.userCurrentLoc?.line || 0,
          function: g.userCurrentLoc?.function?.name || g.userCurrentLoc?.fn?.name || 'unknown',
          pc: g.userCurrentLoc?.pc || 0
        },
        goStatementLoc: {
          file: g.goStatementLoc?.file || 'unknown',
          line: g.goStatementLoc?.line || 0,
          function: g.goStatementLoc?.function?.name || g.goStatementLoc?.fn?.name || 'unknown'
        },
        startLoc: {
          file: g.startLoc?.file || 'unknown',
          line: g.startLoc?.line || 0,
          function: g.startLoc?.function?.name || g.startLoc?.fn?.name || 'unknown'
        },
        threadID: g.threadID || 0,
        status: this.parseGoroutineStatus(g),
        waitReason: g.waitReason || '',
        waitSince: g.waitSince || 0
      }))

      return {
        success: true,
        goroutines: goroutines
      }
    } catch (error) {
      console.error('[DLV Manager] listGoroutines 错误:', error)
      return { success: false, message: error.message }
    }
  }

  /**
   * 解析 Goroutine 状态
   * Delve API 返回的 thread.status 是一个数字:
   * 0 = Idle, 1 = Running, 2 = Sleeping (waiting), 3 = Stopped, 4 = Zombie, 5 = Cgo, 6 = SystemCall
   */
  parseGoroutineStatus(goroutine) {
    // 优先检查 thread 字段中的 status (数字类型)
    if (goroutine.thread && typeof goroutine.thread.status === 'number') {
      const statusMap = {
        0: 'idle',
        1: 'running',
        2: 'waiting',
        3: 'stopped',
        4: 'dead',
        5: 'cgo',
        6: 'syscall'
      }
      return statusMap[goroutine.thread.status] || 'unknown'
    }

    // 如果有字符串类型的 status 字段，直接返回
    if (typeof goroutine.status === 'string') {
      return goroutine.status
    }

    // 如果有数字类型的 status 字段，按照映射表处理
    if (typeof goroutine.status === 'number') {
      const statusMap = {
        0: 'idle',
        1: 'running',
        2: 'waiting',
        3: 'stopped',
        4: 'dead',
        5: 'cgo',
        6: 'syscall'
      }
      return statusMap[goroutine.status] || 'unknown'
    }

    // 推断逻辑：根据其他字段推断状态
    // 有 waitReason 说明在等待
    if (goroutine.waitReason) {
      return 'waiting'
    }

    // 有 threadID 且大于 0，说明可能在运行
    if (goroutine.threadID > 0) {
      return 'running'
    }

    return 'unknown'
  }

  /**
   * 停止调试器
   */
  stopDebugger() {
    return new Promise(async (resolve) => {
      if (!this.dlvProcess) {
        return resolve({ success: true, message: '调试器未运行' })
      }

      // 保存进程引用，因为 cleanup() 会将其置为 null
      const processToKill = this.dlvProcess

      this.emit('output', { type: 'info', data: '正在停止调试器...\n' })

      // 尝试通过 dlv API 优雅地终止被调试进程
      try {
        // Kill=true 会终止被调试的程序
        await this.sendApiRequest('Detach', { Kill: true }, 3000)
        this.emit('output', { type: 'info', data: 'dlv Detach 成功\n' })
      } catch (error) {
        this.emit('output', { type: 'stderr', data: `dlv Detach 失败: ${error.message}\n` })
        // 忽略错误，继续执行强制终止
      }

      // 等待一小段时间让 dlv 和被调试进程退出
      await new Promise(resolve => setTimeout(resolve, 300))

      // 强制终止 dlv 进程（无论 Detach 是否成功）
      try {
        this.emit('output', { type: 'info', data: '终止 dlv 进程...\n' })

        // 先尝试 SIGTERM（优雅终止）
        processToKill.kill('SIGTERM')

        // 等待 1 秒，检查进程是否还存活
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 检查进程是否还在运行（通过尝试发送信号 0）
        try {
          process.kill(processToKill.pid, 0)
          // 如果没有抛出错误，说明进程还活着，使用 SIGKILL
          this.emit('output', { type: 'info', data: '使用 SIGKILL 强制终止...\n' })
          processToKill.kill('SIGKILL')
        } catch (err) {
          // 进程已经不存在，说明 SIGTERM 成功了
          this.emit('output', { type: 'info', data: 'dlv 进程已退出\n' })
        }
      } catch (error) {
        this.emit('output', { type: 'stderr', data: `终止进程失败: ${error.message}\n` })
      }

      this.cleanup()
      resolve({ success: true, message: '调试器已停止' })
    })
  }

  /**
   * 清理资源
   */
  cleanup() {
    // 停止状态轮询
    this.stopStatePolling()

    if (this.dlvClient) {
      this.dlvClient.destroy()
      this.dlvClient = null
    }

    this.dlvProcess = null
    this.currentState = 'stopped'
    this.breakpoints.clear()
    this.responseBuffer = '' // 清空响应缓冲区
  }

  /**
   * 事件发射器方法
   */
  on(event, callback) {
    if (!this.listeners) {
      this.listeners = {}
    }
    if (!this.listeners[event]) {
      this.listeners[event] = []
    }
    this.listeners[event].push(callback)
  }

  removeListener(event, callback) {
    if (this.listeners && this.listeners[event]) {
      const index = this.listeners[event].indexOf(callback)
      if (index > -1) {
        this.listeners[event].splice(index, 1)
      }
    }
  }

  emit(event, data) {
    if (this.listeners && this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(data))
    }
  }

  /**
   * 获取当前状态
   */
  getCurrentState() {
    return this.currentState
  }
}

module.exports = DlvManager
